const Router = require('koa-router')
const fs = require('fs')
const path = require('path')

const send = require('koa-send')
const {createBundleRenderer} = require('vue-server-renderer')
const router = new Router()
const resolve = file => path.resolve(__dirname, file);
const serverBundle = require("../dist/vue-ssr-server-bundle.json");
const clientManifest = require("../dist/vue-ssr-client-manifest.json");
const template = fs.readFileSync(resolve("../dist/index.temp.html"), "utf-8")

const renderer = createBundleRenderer(serverBundle, {
    runInNewContext: false, // 推荐
    template, // （可选）页面模板
    clientManifest // （可选）客户端构建 manifest
})
function renderToString(context) {
    return new Promise((resolve, reject) => {
        renderer.renderToString(context, (err, html) => {
            console.error('err',err)
            err ? reject(err) : resolve(html);
        });
    });
}
// 第 3 步：添加一个中间件来处理所有请求
const handleRequest = async (ctx, next) => {
   try {
       const url = ctx.path

       if (url.includes('.')) {
           let data =  await send(ctx, url, {root: path.resolve(__dirname,'../dist')})
           return await send(ctx, url, {root: path.resolve(__dirname,'../dist')})
       }

       ctx.res.setHeader("Content-Type", "text/html");

       // 将 context 数据渲染为 HTML
       const context = {
           url
       };
       console.log('===>',await renderToString(context))
       return ctx.body = await renderToString(context);
   }catch (e) {
       console.error(e)
   }
}
// router.get('/', (ctx,next)=>{
//     return ctx.body ={
//         title:"123"
//     }
// })
router.get('*',handleRequest)
module.exports = router
